﻿Imports Microsoft.VisualBasic
'Imports System.Web.UI.DataVisualization

Namespace MyUI

    Public Class MasterPageBase
        Inherits System.Web.UI.MasterPage

        'Public Overrides ReadOnly Property Page As PageBase
        '    Get
        '        Return MyBase.Page ' DirectCast(Me.Page, PageBase)
        '    End Get
        'End Property

        Public Overloads ReadOnly Property Page As PageBase
            Get
                Return MyBase.Page ' DirectCast(Me.Page, PageBase)
            End Get
        End Property

        Public Function FC(Of tres As Control)(id As String) As tres

            Return UI.Controls.FindControl(Of tres)(id, Me)

        End Function
    End Class


    Public Class MasterPageBaseSite
        Inherits System.Web.UI.MasterPage

        Public Overloads ReadOnly Property Page As PageBaseSite
            Get
                Return MyBase.Page
            End Get
        End Property

    End Class
    Public Class MasterPageBaseApp
        Inherits MasterPageBase

        Public UpPPrivateMessage As UpdatePanel
        Public UpPPost As UpdatePanel

        Private Sub Page_Init(sender As Object, e As EventArgs) Handles Me.Init

            Me.UpPPrivateMessage = FC(Of UpdatePanel)("UpPPrivateMessage")
            Me.UpPPost = FC(Of UpdatePanel)("UpPPost")

        End Sub
        Public Overloads ReadOnly Property Page As PageBaseApp
            Get
                Return MyBase.Page
            End Get
        End Property



    End Class


    Public Class UserControlBase
        Inherits System.Web.UI.UserControl
        Public ReadOnly Property PageBase As PageBase
            Get
                Return Me.Page
            End Get
        End Property

        Protected Jscript As New StringBuilder

        Private Sub Page_Init(sender As Object, e As EventArgs) Handles Me.Init

            Me.ClientIDMode = Web.UI.ClientIDMode.Predictable

        End Sub

        Protected Sub PageBase_PreRender(sender As Object, e As System.EventArgs) Handles Me.PreRender

            Dim P As PlaceHolder = Me.FindControl("PlhJavaScript")
            If P IsNot Nothing Then
                P.ViewStateMode = Web.UI.ViewStateMode.Disabled
                P.Visible = True
                System.Web.UI.ScriptManager.RegisterStartupScript(Me, Me.GetType, "InitControl" & Me.ClientID, UI.Controls.ToHtml(P), False)
                P.Visible = False

            End If

            'Me.Page.ClientScript.RegisterStartupScript(Me.GetType, "GlobalControl" & Me.ClientID, Me.Jscript.ToString, True)

            System.Web.UI.ScriptManager.RegisterStartupScript(Me, Me.GetType, "GlobalPage", Me.Jscript.ToString, True)

            'Me.Page.ClientScript.

        End Sub
        Public Sub AddJScript(Js As String)
            Me.Jscript.Append(Js)
        End Sub

        Public Property AutoLoad() As Boolean
            Get
                Return Me.ViewState("AutoLoad")
            End Get
            Set(ByVal value As Boolean)
                Me.ViewState("AutoLoad") = value
            End Set
        End Property

    End Class
    Public Class UserControlBaseApp
        Inherits UserControlBase

        Protected ReadOnly Property DB As mDB
            Get
                Return Me.Page.DB
            End Get
        End Property
        Public Overloads ReadOnly Property Page As PageBaseApp
            Get
                Return MyBase.Page ' DirectCast(Me.Page, PageBase)
            End Get
        End Property

        Public ReadOnly Property CurrUser() As mDB.User
            Get
                Return Me.Page.CurrUser
            End Get
        End Property



    End Class

    Public Class Data

        'Public Shared Sub SetRowStatusAccount(controls As List(Of Control), AccountCode As String, CommandName As String)

        '    For Each gr In controls

        '        Dim BtnFollow = UI.Controls.FindControl(Of LinkButton)("BtnFollow", gr.Controls) '   UI.GridRow.GetLinkButton(gr, "BtnFollow")
        '        Dim LblFollower = UI.Controls.FindControl(Of Label)("LblFollower", gr.Controls) '   UI.GridRow.GetLinkButton(gr, "BtnFollow")
        '        'Dim LblFriend = UI.GridRow.GetLabel(gr, "LblFollower")

        '        If BtnFollow.CommandArgument = AccountCode Then


        '            Select Case CommandName
        '                Case "FOLLOW"

        '                    UI.Controls.ClassReplace(BtnFollow, "a-icona1", "a-icona1-a")
        '                    BtnFollow.CommandName = "UNFOLLOW"

        '                Case "UNFOLLOW"

        '                    UI.Controls.ClassReplace(BtnFollow, "a-icona1-a", "a-icona1")
        '                    BtnFollow.CommandName = "FOLLOW"

        '                Case "FOLLOWER"
        '                    UI.Controls.ClassReplace(LblFollower, "a-icona2", "a-icona2-a")


        '            End Select

        '        End If


        '    Next

        'End Sub

        'Public Shared Sub SetListStatusAccount(CurrAccount As mDB.Account, c As List(Of Control), codes As List(Of String), Ids As List(Of Integer))


        '    ' verifica le connessioni
        '    Dim Conn = CurrAccount.GetConnection(codes, Ids, {mDB.Account_Link.Type.FRIENDS, mDB.Account_Link.Type.FOLLOWER})

        '    For Each f In Conn
        '        If f.Type = mDB.Account_Link.Type.FOLLOWER Then
        '            MyUI.Data.SetRowStatusAccount(c, f.AccountCode, "FOLLOWER")
        '        Else
        '            MyUI.Data.SetRowStatusAccount(c, f.AccountCode, "FOLLOW")
        '        End If
        '    Next

        'End Sub

        'Public Shared Sub SetRowStatusAccount(controls As List(Of Control), AccountId As String, CommandName As String)

        '    For Each gr In controls

        '        Dim BtnFollow = UI.Controls.FindControl(Of LinkButton)("BtnFollow", gr.Controls) '   UI.GridRow.GetLinkButton(gr, "BtnFollow")
        '        Dim LblFollower = UI.Controls.FindControl(Of Label)("LblFollower", gr.Controls) '   UI.GridRow.GetLinkButton(gr, "BtnFollow")
        '        'Dim LblFriend = UI.GridRow.GetLabel(gr, "LblFollower")

        '        If BtnFollow.CommandArgument = AccountId Then


        '            Select Case CommandName
        '                Case "FOLLOW"

        '                    UI.Controls.ClassReplace(BtnFollow, "a-icona1", "a-icona1-a")
        '                    BtnFollow.CommandName = "UNFOLLOW"

        '                Case "UNFOLLOW"

        '                    UI.Controls.ClassReplace(BtnFollow, "a-icona1-a", "a-icona1")
        '                    BtnFollow.CommandName = "FOLLOW"

        '                Case "FOLLOWER"
        '                    UI.Controls.ClassReplace(LblFollower, "a-icona2", "a-icona2-a")


        '            End Select

        '        End If


        '    Next

        'End Sub

        Public Shared Sub SetRowFavoritePost(gr As Control, IsFavorite As Boolean)

            Dim BtnFavorite = FC(Of LinkButton)("^BtnFavorite", gr)
            BtnFavorite.CommandName = IIf(IsFavorite, "REMOVE_FAVORITE", "ADD_FAVORITE")
            UI.Controls.ClassSet(BtnFavorite, IsFavorite, "a-icona-stella-a", "a-icona-stella")

        End Sub
        Public Shared Sub SetRowSharedPost(gr As Control, IsShared As Boolean)

            Dim BtnShare = FC(Of LinkButton)("^BtnShare", gr)
            BtnShare.CommandName = IIf(IsShared, "UNSHARE", "SHARE")
            UI.Controls.ClassSet(BtnShare, IsShared, "a-icona-aggiorna-a", "a-icona-aggiorna")

        End Sub
        Public Shared Sub SetRowFriendAccount(gr As Control, IsFriend As Boolean)

            Dim BtnFollow = FC(Of LinkButton)("^BtnFollow", gr)
            BtnFollow.CommandName = IIf(IsFriend, "UNFOLLOW", "FOLLOW")
            UI.Controls.ClassSet(BtnFollow, IsFriend, "a-icona1-a", "a-icona1")


        End Sub
        Public Shared Sub SetRowFollowerAccount(gr As Control, IsFollower As Boolean)

            Dim LblFollower = FC(Of Label)("^LblFollower", gr) '   UI.GridRow.GetLinkButton(gr, "BtnFollow")
            UI.Controls.ClassSet(LblFollower, IsFollower, "a-icona2-a", "a-icona2")

            Dim BtnOpenPrivate = FC(Of LinkButton)("^BtnOpenPrivate", gr) '   UI.GridRow.GetLinkButton(gr, "BtnFollow")
            If BtnOpenPrivate IsNot Nothing Then
                ' BtnOpenPrivate.Visible = IsFollower

            End If
            'BtnOpenPrivate


        End Sub

        Public Shared Sub SetRowStatusQuery(gr As Control, data As mDB.Query)

            Dim LblStatus = FC(Of Label)("LblStatus", gr)

            Select Case data.UpdateStatus
                Case mDB.Query.UpdateStatusType.QUEUED

                    LblStatus.Text = "pending"
                    UI.Controls.ClassAdd(LblStatus, "en-pending")

                    Select Case data.DataStatus
                        Case mDB.Query.DataStausType.EMPTY
                            UI.Controls.ClassAdd(LblStatus, "en-empty")
                    End Select

                Case Else

                    LblStatus.Text = "ready"
                    UI.Controls.ClassAdd(LblStatus, "en-ready")

                    Select Case data.DataStatus
                        Case mDB.Query.DataStausType.EMPTY
                            LblStatus.Text = "empty"
                            UI.Controls.ClassAdd(LblStatus, "en-empty")
                    End Select

            End Select

        End Sub
        Public Shared Sub SetRowStatusProfile(gr As Control, data As mDB.Profile)

            Dim LblStatus = FC(Of Label)("LblStatus", gr)

            Select Case data.UpdateStatus
                Case mDB.Query.UpdateStatusType.QUEUED
                    LblStatus.Text = "pending"
                    UI.Controls.ClassAdd(LblStatus, "en-pending")

                    Select Case data.DataStatus
                        Case mDB.Query.DataStausType.EMPTY
                            UI.Controls.ClassAdd(LblStatus, "en-empty")
                    End Select

                Case Else
                    LblStatus.Text = "ready"
                    UI.Controls.ClassAdd(LblStatus, "en-ready")

                    Select Case data.DataStatus
                        Case mDB.Query.DataStausType.EMPTY
                            LblStatus.Text = "empty"
                            UI.Controls.ClassAdd(LblStatus, "en-empty")
                    End Select

            End Select
        End Sub

        Public Shared Sub SetListStatusPost(CurrAccount As mDB.Account, controls As List(Of Control), PostCodes As List(Of String))

            Dim PostCodesDist = PostCodes.Distinct.ToList
            Dim Favorite = CurrAccount.Tab_Favorite_Post.Where("post_code", "IN", PostCodesDist).ToDictionary(Of String)("post_code")
            Dim Share = CurrAccount.Tab_Share_Detail.REL.Share_Detail.Share_Post.Where("Share_Post.post_code", "IN", PostCodesDist).SetSelect("Share_Post.post_code").ToDictionary(Of String)("post_code")

            For Each gr In controls
                Dim PostCode = PostCodesDist(UI.Controls.GetIndexData(gr))  '    i.DataItemIndex)   '  dd(UI.ListDataItem.GetIndexData(gr))

                SetRowFavoritePost(gr, Favorite.ContainsKey(PostCode))
                SetRowSharedPost(gr, Share.ContainsKey(PostCode))

            Next

        End Sub

        Public Shared Sub SetListStatusAccount(CurrAccount As mDB.Account, controls As List(Of Control), AccCodes As List(Of String))

            Dim AccCodesDist = AccCodes.Distinct.ToList
            If AccCodesDist.Count > 0 Then
                Dim Followers = CurrAccount.View_AccountLink(AccCodesDist, Nothing, mDB._Account_Link.Type.FOLLOWER).ToDictionary(Of String)("account_code")
                Dim Friends = CurrAccount.View_AccountLink(AccCodesDist, Nothing, mDB._Account_Link.Type.FRIENDS).ToDictionary(Of String)("account_code")

                For Each gr In controls
                    'UI.ListDataItem.GetIndexData()
                    Dim AccCode = AccCodes(UI.Controls.GetIndexData(gr))  '    i.DataItemIndex)   '  dd(UI.ListDataItem.GetIndexData(gr))

                    MyUI.Data.SetRowFriendAccount(gr, Friends.ContainsKey(AccCode))
                    MyUI.Data.SetRowFollowerAccount(gr, Followers.ContainsKey(AccCode))

                Next
            End If

        End Sub

        Public Shared Sub SetListCatAccount(CurrAccount As mDB.Account, controls As List(Of Control), AccCodes As List(Of Integer))

            Dim AccCodesDist = AccCodes.Distinct.ToList

            If AccCodesDist.Count > 0 Then

                Dim cat = CurrAccount.View_Categorize.ToDictionary(Of Integer)("id")
                Dim catacc As New Dictionary(Of Integer, List(Of mDB.Categorize))
                Dim cat2 = CurrAccount.Tab_Categorize_Account.Where("account_categozie_id", "IN", AccCodesDist).ToList
                For Each c In cat2
                    If Not catacc.ContainsKey(c.Account_Categozie_Id) Then
                        catacc.Add(c.Account_Categozie_Id, New List(Of mDB.Categorize))
                    End If
                    If cat.ContainsKey(c.Categorize_Id) Then
                        catacc(c.Account_Categozie_Id).Add(cat(c.Categorize_Id))
                    End If
                Next


                For Each gr In controls
                    Dim AccCode = AccCodes(UI.Controls.GetIndexData(gr))  '    i.DataItemIndex)   '  dd(UI.ListDataItem.GetIndexData(gr))

                    If catacc.ContainsKey(AccCode) Then
                        Dim LblCats = FC(Of Label)("LblCats", gr) '   UI.GridRow.GetLinkButton(gr, "BtnFollow")
                        LblCats.Text = String.Join(" - ", catacc(AccCode).Select(Function(o) o.Description))

                    End If


                Next
            End If

        End Sub

        'Public Shared Sub SetListFriendAccount(controls As List(Of Control), AccCode As String, isFriend As Boolean)

        '    For Each gr In controls

        '        Dim HidAccountCode = UI.Controls.FindControl(Of HiddenField)("HidAccountCode", gr.Controls) '   UI.GridRow.GetLinkButton(gr, "BtnFollow")
        '        If HidAccountCode IsNot Nothing AndAlso HidAccountCode.Value = AccCode Then
        '            MyUI.Data.SetRowFriendAccount(gr, isFriend)
        '        End If

        '    Next

        'End Sub


        'Public Shared Sub aaaa(CurrAccount As mDB.Account, controls As List(Of Control), f As Func(Of Object, String))

        '    Dim bb As IDataBoundControl = controls(0).Parent

        '    Dim DataList As List(Of Object) = bb.DataSource '   = UI.ListData.GetDataList(Of Object)(controls(0).Parent.datasource)

        '    'Dim PostCodes = UI.ListData.GetDataList(Of Object)(Me.ListMessage).Select(Function(o) o.post.Post_Code).Distinct.ToList
        '    Dim PostCodes = DataList.Select(f).Distinct.ToList
        '    Dim Favorite = CurrAccount.Tab_Favorite_Post.Where("post_code", "IN", PostCodes).ToDictionary(Of String)("post_code")

        '    For Each gr In controls
        '        Dim i As IDataItemContainer = gr 'Dim Data = UI.ListDataItem.GetData(Of Object)(gr) '  dd(UI.ListDataItem.GetIndexData(gr))
        '        Dim Data = DataList(i.DataItemIndex)   '  dd(UI.ListDataItem.GetIndexData(gr))


        '        Dim BtnFavorite = UI.ListDataItem.GetControl(Of LinkButton)(gr, "BtnFavorite")
        '        If Favorite.ContainsKey(Data.post.Post_Code) Then
        '            UI.Controls.ClassReplace(BtnFavorite, "a-icona-stella", "a-icona-stella-a")
        '        End If

        '    Next

        'End Sub




        'Public Shared Sub aaaa3(CurrAccount As mDB.Account, controls As List(Of Control))

        '    ' IDataBoundListControl
        '    Dim kk As IDataBoundListControl = controls(0).Parent

        '    Dim AccCodes As New List(Of String)
        '    For Each gr In controls

        '        Dim ii As IDataItemContainer = gr
        '        AccCodes.Add(kk.DataKeys(ii.DataItemIndex).Values("account_code").ToString())

        '        'Dim HidAccountCode = UI.Controls.FindControl(Of HiddenField)("HidAccountCode", gr.Controls) '   UI.GridRow.GetLinkButton(gr, "BtnFollow")
        '        'Dim objdata = MyApp.JSONDeserialize(UI.Controls.GetHiddenValue(UI.Controls.FindControl(Of HiddenField)("HidData", gr.Controls)))
        '        'AccCodes.Add(objdata("account_code"))

        '    Next


        '    ' verifica le connessioni
        '    Dim Conn = CurrAccount.GetConnection(AccCodes, Nothing, {mDB.Account_Link.Type.FRIENDS, mDB.Account_Link.Type.FOLLOWER})

        '    For Each gr In controls

        '        Dim BtnFollow = UI.Controls.FindControl(Of LinkButton)("BtnFollow", gr.Controls) '   UI.GridRow.GetLinkButton(gr, "BtnFollow")
        '        Dim LblFollower = UI.Controls.FindControl(Of Label)("LblFollower", gr.Controls) '   UI.GridRow.GetLinkButton(gr, "BtnFollow")
        '        'Dim HidAccountCode = UI.Controls.FindControl(Of HiddenField)("HidAccountCode", gr.Controls)
        '        'Dim LblFriend = UI.GridRow.GetLabel(gr, "LblFollower")
        '        Dim objdata = MyApp.JSONDeserialize(UI.Controls.GetHiddenValue(UI.Controls.FindControl(Of HiddenField)("HidData", gr.Controls)))

        '        Dim AccountCode = objdata("account_code")  '.CommandArgument

        '        If Conn.ContainsKey(AccountCode) Then

        '            If Conn(AccountCode).Types.ContainsKey(GloukDB.Account_Link.Type.FOLLOWER) Then
        '                UI.Controls.ClassReplace(LblFollower, "a-icona2", "a-icona2-a")
        '            End If

        '            If Conn(AccountCode).Types.ContainsKey(GloukDB.Account_Link.Type.FRIENDS) Then
        '                UI.Controls.ClassReplace(BtnFollow, "a-icona1", "a-icona1-a")
        '                BtnFollow.CommandName = "UNFOLLOW"
        '            End If
        '        Else
        '            UI.Controls.ClassReplace(LblFollower, "a-icona2-a", "a-icona2")
        '            UI.Controls.ClassReplace(BtnFollow, "a-icona1-a", "a-icona1")
        '            BtnFollow.CommandName = "FOLLOW"

        '        End If

        '    Next

        'End Sub


        'Public Shared Sub SetListStatusAccount(CurrAccount As mDB.Account, controls As List(Of Control))

        '    Dim AccCodes As New List(Of String)
        '    For Each gr In controls
        '        'Dim HidAccountCode = UI.Controls.FindControl(Of HiddenField)("HidAccountCode", gr.Controls) '   UI.GridRow.GetLinkButton(gr, "BtnFollow")
        '        Dim objdata = MyApp.JSONDeserialize(UI.Controls.GetHiddenValue(UI.Controls.FindControl(Of HiddenField)("HidData", gr.Controls)))
        '        AccCodes.Add(objdata("account_code"))

        '    Next


        '    ' verifica le connessioni
        '    Dim Conn = CurrAccount.GetConnection(AccCodes, Nothing, {mDB.Account_Link.Type.FRIENDS, mDB.Account_Link.Type.FOLLOWER})

        '    For Each gr In controls

        '        Dim BtnFollow = UI.Controls.FindControl(Of LinkButton)("BtnFollow", gr.Controls) '   UI.GridRow.GetLinkButton(gr, "BtnFollow")
        '        Dim LblFollower = UI.Controls.FindControl(Of Label)("LblFollower", gr.Controls) '   UI.GridRow.GetLinkButton(gr, "BtnFollow")
        '        'Dim HidAccountCode = UI.Controls.FindControl(Of HiddenField)("HidAccountCode", gr.Controls)
        '        'Dim LblFriend = UI.GridRow.GetLabel(gr, "LblFollower")
        '        Dim objdata = MyApp.JSONDeserialize(UI.Controls.GetHiddenValue(UI.Controls.FindControl(Of HiddenField)("HidData", gr.Controls)))

        '        Dim AccountCode = objdata("account_code")  '.CommandArgument

        '        If Conn.ContainsKey(AccountCode) Then

        '            If Conn(AccountCode).Types.ContainsKey(GloukDB.Account_Link.Type.FOLLOWER) Then
        '                UI.Controls.ClassReplace(LblFollower, "a-icona2", "a-icona2-a")
        '            End If

        '            If Conn(AccountCode).Types.ContainsKey(GloukDB.Account_Link.Type.FRIENDS) Then
        '                UI.Controls.ClassReplace(BtnFollow, "a-icona1", "a-icona1-a")
        '                BtnFollow.CommandName = "UNFOLLOW"
        '            End If
        '        Else
        '            UI.Controls.ClassReplace(LblFollower, "a-icona2-a", "a-icona2")
        '            UI.Controls.ClassReplace(BtnFollow, "a-icona1-a", "a-icona1")
        '            BtnFollow.CommandName = "FOLLOW"

        '        End If

        '    Next

        'End Sub

        'Public Shared Sub SetListStatusPost(CurrAccount As mDB.Account, controls As List(Of Control))

        '    Dim AccCodes As New List(Of String)
        '    For Each gr In controls
        '        'Dim HidAccountCode = UI.Controls.FindControl(Of HiddenField)("HidAccountCode", gr.Controls) '   UI.GridRow.GetLinkButton(gr, "BtnFollow")
        '        Dim objdata = MyApp.JSONDeserialize(UI.Controls.GetHiddenValue(UI.Controls.FindControl(Of HiddenField)("HidData", gr.Controls)))
        '        AccCodes.Add(objdata("post_code"))

        '    Next


        '    ' verifica le connessioni
        '    'Dim Conn = CurrAccount.GetConnection(AccCodes, Nothing, {mDB.Account_Link.Type.FRIENDS, mDB.Account_Link.Type.FOLLOWER})
        '    Dim Conn = CurrAccount.Tab_Favorite_Post.ToDictionary(Of String)("post_code")

        '    For Each gr In controls

        '        Dim BtnFollow = UI.Controls.FindControl(Of LinkButton)("BtnFollow", gr.Controls) '   UI.GridRow.GetLinkButton(gr, "BtnFollow")
        '        Dim LblFollower = UI.Controls.FindControl(Of Label)("LblFollower", gr.Controls) '   UI.GridRow.GetLinkButton(gr, "BtnFollow")
        '        'Dim HidAccountCode = UI.Controls.FindControl(Of HiddenField)("HidAccountCode", gr.Controls)
        '        'Dim LblFriend = UI.GridRow.GetLabel(gr, "LblFollower")
        '        Dim objdata = MyApp.JSONDeserialize(UI.Controls.GetHiddenValue(UI.Controls.FindControl(Of HiddenField)("HidData", gr.Controls)))

        '        Dim post_code = objdata("post_code")  '.CommandArgument

        '        If Conn.ContainsKey(post_code) Then

        '            UI.Controls.ClassReplace(BtnFollow, "a-icona1", "a-icona1-a")
        '            BtnFollow.CommandName = "UNFOLLOW"
        '        Else

        '            UI.Controls.ClassReplace(BtnFollow, "a-icona1-a", "a-icona1")
        '            BtnFollow.CommandName = "FOLLOW"

        '        End If

        '    Next

        'End Sub


        'Public Shared Sub SetListStatusAccount(CurrAccount As mDB.Account, controls As List(Of Control), codes As List(Of String), Ids As List(Of Integer))


        '    ' verifica le connessioni
        '    Dim Conn = CurrAccount.GetConnection(codes, Ids, {mDB.Account_Link.Type.FRIENDS, mDB.Account_Link.Type.FOLLOWER})

        '    For Each gr In controls

        '        Dim BtnFollow = UI.Controls.FindControl(Of LinkButton)("BtnFollow", gr.Controls) '   UI.GridRow.GetLinkButton(gr, "BtnFollow")
        '        Dim LblFollower = UI.Controls.FindControl(Of Label)("LblFollower", gr.Controls) '   UI.GridRow.GetLinkButton(gr, "BtnFollow")
        '        'Dim LblFriend = UI.GridRow.GetLabel(gr, "LblFollower")
        '        Dim AccountCode = BtnFollow.CommandArgument
        '        If Conn.ContainsKey(AccountCode) Then

        '            If Conn(AccountCode).ContainsKey(GloukDB.Account_Link.Type.FOLLOWER) Then
        '                UI.Controls.ClassReplace(LblFollower, "a-icona2", "a-icona2-a")
        '            Else

        '            End If

        '            If Conn(AccountCode).ContainsKey(GloukDB.Account_Link.Type.FRIENDS) Then
        '                UI.Controls.ClassReplace(BtnFollow, "a-icona1", "a-icona1-a")
        '                BtnFollow.CommandName = "UNFOLLOW"
        '            Else
        '                UI.Controls.ClassReplace(BtnFollow, "a-icona1-a", "a-icona1")
        '                BtnFollow.CommandName = "FOLLOW"
        '            End If

        '        End If

        '        'If BtnFollow.CommandArgument = AccountId Then


        '        '    Select Case CommandName
        '        '        Case "FOLLOW"

        '        '            UI.Controls.ClassReplace(BtnFollow, "a-icona1", "a-icona1-a")
        '        '            BtnFollow.CommandName = "UNFOLLOW"

        '        '        Case "UNFOLLOW"

        '        '            UI.Controls.ClassReplace(BtnFollow, "a-icona1-a", "a-icona1")
        '        '            BtnFollow.CommandName = "FOLLOW"

        '        '        Case "FOLLOWER"
        '        '            UI.Controls.ClassReplace(LblFollower, "a-icona2", "a-icona2-a")


        '        '    End Select

        '        'End If


        '    Next


        '    'For Each f In Conn
        '    '    If f.Type = mDB.Account_Link.Type.FOLLOWER Then
        '    '        MyUI.Data.SetRowStatusAccount(c, f.AccountCode, "FOLLOWER")
        '    '    Else
        '    '        MyUI.Data.SetRowStatusAccount(c, f.AccountCode, "FOLLOW")
        '    '    End If
        '    'Next

        'End Sub

        'Public Shared Sub SetRowStatusAccount2(controls As List(Of Control), AccountId As String, CommandName As String)

        '    For Each gr In controls

        '        Dim BtnFollow = UI.Controls.FindControl(Of LinkButton)("BtnFollow", gr.Controls) '   UI.GridRow.GetLinkButton(gr, "BtnFollow")
        '        Dim LblFollower = UI.Controls.FindControl(Of Label)("LblFollower", gr.Controls) '   UI.GridRow.GetLinkButton(gr, "BtnFollow")
        '        'Dim LblFriend = UI.GridRow.GetLabel(gr, "LblFollower")

        '        If BtnFollow.CommandArgument = AccountId Then


        '            Select Case CommandName
        '                Case "FOLLOW"

        '                    UI.Controls.ClassReplace(BtnFollow, "a-icona1", "a-icona1-a")
        '                    BtnFollow.CommandName = "UNFOLLOW"

        '                Case "UNFOLLOW"

        '                    UI.Controls.ClassReplace(BtnFollow, "a-icona1-a", "a-icona1")
        '                    BtnFollow.CommandName = "FOLLOW"

        '                Case "FOLLOWER"
        '                    UI.Controls.ClassReplace(LblFollower, "a-icona2", "a-icona2-a")


        '            End Select

        '        End If


        '    Next

        'End Sub

    End Class
 
    Public Class Print

        Public Shared Function Post(p As String) As String

            p = p.ToString

            p = Replace(p, vbCrLf, " ")
            p = Replace(p, Chr(160), " ")
            p = Replace(p, "&nbsp;", " ")

            If p <> "" Then
                p = Regex.Replace(p, "\B#\w*[a-zA-Z]+\w*", "<b>$0</b>")
            End If
            If p <> "" Then
                p = Regex.Replace(p, "((http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?)", "<a href=""$0"" class=""re-tweet"" target=""_blank"">[LINK]</a>")
            End If


            Return p

        End Function

        Public Shared Function DateDayMonth(d As Date) As String

            If d = Date.MinValue Then
                Return "-"
            Else
                Return Format(d, "dd MMMM")
            End If

        End Function
        Public Shared Function DateMonthDay(d As Date) As String

            If d = Date.MinValue Then
                Return "-"
            Else
                Return Format(d, "MMM dd")
            End If

        End Function
        Public Shared Function DateInput(d As Date) As String

            If d = Date.MinValue Then
                Return ""
            Else
                Return Format(d, "yyyy-MM-dd")
            End If

        End Function

        Public Shared Function DateShort(d As Date) As String
            If d = Date.MinValue Then
                Return "-"
            Else
                Return Format(d, "dd/MM/yy")
            End If

        End Function
        Public Shared Function DateShort2(d As Date) As String

            If d = Date.MinValue Then
                Return "-"
            Else
                Return Format(d, "dd MMM yy")
            End If

        End Function
        Public Shared Function DateShortNoYear(d As Date) As String

            If d = Date.MinValue Then
                Return "-"
            Else
                If Now.Year <> d.Year Then
                    Return Format(d, "dd MMM yyyy")
                Else
                    Return Format(d, "dd MMM")
                End If
            End If

        End Function

        Public Shared Function DateLong(d As Date) As String

            If d = Date.MinValue Then
                Return "-"
            Else
                Return Format(d, "dddd dd MMMM yyyy")
            End If

        End Function
        Public Shared Function DateLong2(d As Date) As String

            If d = Date.MinValue Then
                Return "-"
            Else
                Return Format(d, "MMMM dd, yyyy")
            End If

        End Function

        Public Shared Function DateTimeShort(d As Date) As String

            If d = Date.MinValue Then
                Return "-"
            Else
                Return Format(d, "dd/MM/yy HH:mm")
            End If
        End Function
        Public Shared Function DateTimeLong(d As Date) As String

            If d = Date.MinValue Then
                Return "-"
            Else
                Return Format(d, "dddd dd MMMM yyyy, HH:mm")
            End If
        End Function
        Public Shared Function DateTimeLong2(d As Date) As String

            If d = Date.MinValue Then
                Return "-"
            Else
                Return Format(d, "dd MMMM yyyy, HH:mm")
            End If
        End Function

        Public Shared Function TimeShort(d As Date) As String

            If d = Date.MinValue Then
                Return "-"
            Else
                Return Format(d, "HH:mm")
            End If
        End Function
        Public Shared Function TimeLong(d As Date) As String

            If d = Date.MinValue Then
                Return "-"
            Else
                Return Format(d, "HH:mm:ss")
            End If
        End Function
        Public Shared Function TimeNow(d As Date) As String

            Dim diff = Now.Subtract(d)
            Dim SecDiff = Math.Max(diff.TotalSeconds, 1)
            Select Case SecDiff

                Case Is < 60
                    Return SF("{0} s", Math.Round(SecDiff))
                Case Is < 60 * 60
                    Return SF("{0} m", Math.Round(diff.TotalMinutes))
                Case Is < 60 * 60 * 24
                    Return SF("{0} h", Math.Round(diff.TotalHours))
                Case Else
                    Return SF("{0}", Print.DateShortNoYear(d))

            End Select


            ' {}
        End Function
        Public Shared Function TimeNow2(d As Date) As String

            Dim diff = Now.Subtract(d)
            Dim SecDiff = Math.Max(diff.TotalSeconds, 1)
            Select Case SecDiff

                Case Is < 60
                    Return SF("{0} seconds", Math.Round(SecDiff))
                Case Is < 60 * 60
                    Return SF("{0} minutes", Math.Round(diff.TotalMinutes))
                Case Else
                    Return SF("{0} hours", Math.Round(diff.TotalHours))

            End Select


            ' {}
        End Function

        Public Shared Function DayWeek(d As Integer) As String

            Dim w As DayOfWeek = d

            Return w.ToString()

        End Function
        Public Shared Function DaysWeekShort(d As Dictionary(Of String, Integer)) As String

            Dim dd = From day In d Where day.Value = 1 Select DayWeek(day.Key).Substring(0, 1)

            If dd.Count < 7 Then
                Return String.Join(" ", dd)
            Else
                Return "every day"
            End If

        End Function

    End Class

    Public Class Print2

        Public UtcOffset As Integer

        'Public Sub New()

        'End Sub
        Public Sub New()

        End Sub

        'TimeZoneInfo.GetSystemTimeZones()
        Public Sub New(UtcOffset As Integer)
            Me.UtcOffset = UtcOffset
        End Sub

        Public Function Post(p As String) As String

            p = p.ToString

            p = Replace(p, vbCrLf, " ")
            p = Replace(p, Chr(160), " ")
            p = Replace(p, "&nbsp;", " ")

            If p <> "" Then
                p = Regex.Replace(p, "\B#\w*[a-zA-Z]+\w*", "<b>$0</b>")
            End If
            If p <> "" Then
                p = Regex.Replace(p, "((http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?)", "<a href=""$0"" class=""re-tweet"" target=""_blank"">[LINK]</a>")
            End If


            Return p

        End Function

        Public Function DateDayMonth(d As Date) As String

            If d = Date.MinValue Then
                Return "-"
            Else
                Return Format(d.AddSeconds(Me.UtcOffset), "dd MMMM")
            End If

        End Function
        Public Function DateMonthDay(d As Date) As String

            If d = Date.MinValue Then
                Return "-"
            Else
                Return Format(d.AddSeconds(Me.UtcOffset), "MMM dd")
            End If

        End Function
        Public Function DateInput(d As Date) As String

            If d = Date.MinValue Then
                Return ""
            Else
                Return Format(d.AddSeconds(Me.UtcOffset), "yyyy-MM-dd")
            End If

        End Function

        Public Function DateShort(d As Date) As String
            If d = Date.MinValue Then
                Return "-"
            Else
                Return Format(d.AddSeconds(Me.UtcOffset), "dd/MM/yy")
            End If

        End Function
        Public Function DateShort2(d As Date) As String

            If d = Date.MinValue Then
                Return "-"
            Else
                Return Format(d.AddSeconds(Me.UtcOffset), "dd MMM yy")
            End If

        End Function
        Public Function DateShortNoYear(d As Date) As String

            If d = Date.MinValue Then
                Return "-"
            Else
                d = d.AddSeconds(Me.UtcOffset)
                If Date.UtcNow.Year <> d.Year Then
                    Return Format(d, "dd MMM yyyy")
                Else
                    Return Format(d, "dd MMM")
                End If
            End If

        End Function

        Public Function DateLong(d As Date) As String

            If d = Date.MinValue Then
                Return "-"
            Else
                Return Format(d.AddSeconds(Me.UtcOffset), "dddd dd MMMM yyyy")
            End If

        End Function
        Public Function DateLong2(d As Date) As String

            If d = Date.MinValue Then
                Return "-"
            Else
                Return Format(d.AddSeconds(Me.UtcOffset), "MMMM dd, yyyy")
            End If

        End Function

        Public Function DateTimeShort(d As Date) As String

            If d = Date.MinValue Then
                Return "-"
            Else
                Return Format(d.AddSeconds(Me.UtcOffset), "dd/MM/yy HH:mm")
            End If
        End Function
        Public Function DateTimeLong(d As Date) As String

            If d = Date.MinValue Then
                Return "-"
            Else
                Return Format(d.AddSeconds(Me.UtcOffset), "dddd dd MMMM yyyy, HH:mm")
            End If
        End Function
        Public Function DateTimeLong2(d As Date) As String

            If d = Date.MinValue Then
                Return "-"
            Else
                Return Format(d.AddSeconds(Me.UtcOffset), "dd MMMM yyyy, HH:mm")
            End If
        End Function

        Public Function TimeShort(d As Date) As String

            If d = Date.MinValue Then
                Return "-"
            Else
                Return Format(d.AddSeconds(Me.UtcOffset), "HH:mm")
            End If
        End Function
        Public Function TimeLong(d As Date) As String

            If d = Date.MinValue Then
                Return "-"
            Else
                Return Format(d.AddSeconds(Me.UtcOffset), "HH:mm:ss")
            End If
        End Function
        Public Function TimeNow(d As Date) As String

            Dim diff = Date.UtcNow.Subtract(d)
            Dim SecDiff = Math.Max(diff.TotalSeconds, 1)
            Select Case SecDiff

                Case Is < 60
                    Return SF("{0} s", Math.Round(SecDiff))
                Case Is < 60 * 60
                    Return SF("{0} m", Math.Round(diff.TotalMinutes))
                Case Is < 60 * 60 * 24
                    Return SF("{0} h", Math.Round(diff.TotalHours))
                Case Else
                    Return SF("{0}", Print.DateShortNoYear(d))

            End Select


            ' {}
        End Function
        Public Function TimeNow2(d As Date) As String

            Dim diff = Date.UtcNow.Subtract(d)
            Dim SecDiff = Math.Max(diff.TotalSeconds, 1)
            Select Case SecDiff

                Case Is < 60
                    Return SF("{0} seconds", Math.Round(SecDiff))
                Case Is < 60 * 60
                    Return SF("{0} minutes", Math.Round(diff.TotalMinutes))
                Case Else
                    Return SF("{0} hours", Math.Round(diff.TotalHours))

            End Select


            ' {}
        End Function

        Public Function DayWeek(d As Integer) As String

            Dim w As DayOfWeek = d

            Return w.ToString()

        End Function
        Public Function DaysWeekShort(d As Dictionary(Of String, Integer)) As String

            Dim dd = From day In d Where day.Value = 1 Select DayWeek(day.Key).Substring(0, 1)

            If dd.Count < 7 Then
                Return String.Join(" ", dd)
            Else
                Return "every day"
            End If

        End Function

    End Class


    Public Class PageBase
        Inherits System.Web.UI.Page

        Protected JsVar As New Dictionary(Of String, Object)(StringComparer.CurrentCultureIgnoreCase)
        Protected Jscript As New StringBuilder
        Protected Browser As Browser
        Protected PageUIValidator As New UI.Validator.ValidatorGroup
        'Dim varjs As New Dictionary(Of String, Object)


        Protected Sub PageBase_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init

            Me.Browser = New Browser



        End Sub
        Protected Sub PageBase_PreRenderComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRenderComplete
#If DEBUG Then

        'Response.Write("<hr>" & mDB.UrbiStat.GetDB.Log.ToString.Replace(vbCrLf, "<br>") & "<hr>")

#End If

        End Sub
        Protected Sub PageBase_PreRender(sender As Object, e As System.EventArgs) Handles Me.PreRender

            'Me.Page.ClientScript.RegisterStartupScript(Me.GetType, "GlobalPage", Me.Jscript.ToString, True)

            AddJScript("var var_server = " & MyApp.JSONSerialize(JsVar) & ";")

            System.Web.UI.ScriptManager.RegisterStartupScript(Me, Me.GetType, "GlobalPage", Me.Jscript.ToString, True)


            'Me.Page.ClientScript.

        End Sub
        Public Sub AddJScript(Js As String)
            Me.Jscript.Append(Js)
        End Sub

        <Services.WebMethod()> _
        Public Shared Function get_json_data_session(ByVal key As String) As String

            Dim data = HttpContext.Current.Session(key)
            Dim json = MyApp.JSONSerialize(data)
            HttpContext.Current.Session(key) = Nothing

            Return json

        End Function

    End Class



    Public Class PageBaseApp
        Inherits PageBase

        Public DB As mDB

        Public CurrUser As mDB.User
        Public CurrRoute As UI.Route

        Protected LogTime As New LogTime
        Protected ExcelFileName As String
        Protected IsExcelPage As Boolean = False

        Public Overloads ReadOnly Property Master As MasterPageBaseApp
            Get
                Return MyBase.Master
            End Get
        End Property

        'Protected Overrides ReadOnly Property PageStatePersister As PageStatePersister
        '    Get
        '        Return New SessionPageStatePersister(Me)
        '    End Get
        'End Property

        Private Sub PageBaseApp_Init(sender As Object, e As System.EventArgs) Handles Me.Init


            Me.IsExcelPage = UI.Page.GetValue("E") <> ""

            DB = mDB.GetDB

            CurrUser = MyApp.GetUser(False)

            If Not Me.IsPostBack Then
                If CurrUser IsNot Nothing Then
                    CurrUser.Session.CurrPage = CurrRoute.RouteName
                End If
            End If

            Me.LogTime.AddLog("INIT PAGINA")

        End Sub

        Private Sub PageBaseApp_InitComplete(sender As Object, e As System.EventArgs) Handles Me.InitComplete

            If Me.Browser.Type = MyUI.Browser.BroserType.Mobile And MobileRedirect Then
                'Dim uu As New UriBuilder(Request.Url)
                'uu.Path = "/Mobile" & uu.Path
                'Response.Redirect(uu.Uri.AbsoluteUri)
            End If



        End Sub

        Private Sub PageBaseApp_PreInit(sender As Object, e As System.EventArgs) Handles Me.PreInit

            CurrRoute = New UI.Route(Me.Page)


            'Dim c As Globalization.CultureInfo
            'c = Globalization.CultureInfo.CreateSpecificCulture(Session("CurrLang").ToString.ToLower)
            'Threading.Thread.CurrentThread.CurrentCulture = c
            'Threading.Thread.CurrentThread.CurrentUICulture = c

            ''Threading.Thread.CurrentThread.CurrentCulture = Globalization.CultureInfo.CreateSpecificCulture(Session("CurrLang").ToString.ToLower)
            ''Threading.Thread.CurrentThread.CurrentUICulture = Threading.Thread.CurrentThread.CurrentCulture


        End Sub
        Protected Overrides Sub InitializeCulture()
            If Utils.GetValue(Request.QueryString, "ln") <> "" Then
                Session("CurrLang") = Utils.GetValue(Request.QueryString, "ln")
            End If
            If Session("CurrLang") = "" Then
                Session("CurrLang") = "EN"
            End If

            Dim c As Globalization.CultureInfo
            c = Globalization.CultureInfo.CreateSpecificCulture(Session("CurrLang").ToString.ToLower)
            Threading.Thread.CurrentThread.CurrentCulture = c
            Threading.Thread.CurrentThread.CurrentUICulture = c

            MyBase.InitializeCulture()

        End Sub
        Protected Sub PageBaseApp_PreRenderComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRenderComplete

            If CurrUser IsNot Nothing Then
                'CurrUser.SaveSessionData()
                CurrUser.SessionSave()
                'CurrUser.Session = CurrUser.Session
                'Me.Session_Data_Json = MyApp.JSONSerialize(Me.SessionData)
                'Data_Json.SaveObj(DB, Me.Session_Data_Id, Me.SessionData)
                'DB.SubmitChanges()
                'CurrUser.SessionData = CurrUser.SessionData
            End If

            Me.DB = Nothing
#If DEBUG Then

            Me.LogTime.AddLog("RENDER COMPLETA PAGINA")

            If Me.Form IsNot Nothing Then
                Dim P As Panel = Me.Form.FindControl("PnlLogTime")
                If P IsNot Nothing Then
                    Dim g As New GridView With {.AutoGenerateColumns = True}
                    UI.Grid.Bind(g, Me.LogTime.LogTime)

                    P.Visible = True
                    P.Controls.Add(g)

                End If
            End If
#End If

        End Sub

        Protected Overrides Sub Render(writer As HtmlTextWriter)

            If Not Me.IsExcelPage Then
                'Dim tt As New IO.StreamWriter(Response.OutputStream, Text.Encoding.UTF8)
                'Dim htmlWriter2 As New HtmlTextWriter(tt)
                'MyBase.Render(htmlWriter2)
                'tt.Flush()
                MyBase.Render(writer)
            Else
                Dim sb As New System.Text.StringBuilder()
                Dim sw As New IO.StringWriter(sb)
                Dim htmlWriter As New HtmlTextWriter(sw)

                MyBase.Render(htmlWriter)

                Dim PageHTML = "" ' Excel.Functions.ToHtml(sb.ToString)

                Response.AppendHeader("Content-Disposition", "attachment; filename=" & ExcelFileName & ".xls")
                Response.ContentType = "application/ms-excel"


                writer.Write(PageHTML)

            End If

        End Sub


        Private _MobileRedirect As Boolean = True
        Public Property MobileRedirect() As Boolean
            Get
                Return _MobileRedirect
            End Get
            Set(ByVal value As Boolean)
                _MobileRedirect = value
            End Set
        End Property



    End Class

    Public Class PageBaseSite
        Inherits PageBase

        Public DB As mDB


        Public CurrRoute As UI.Route
        'Public CurrMainApp As MyApp.MainApptype

        Protected Sub PageBaseSite_Init(sender As Object, e As System.EventArgs) Handles Me.Init


            CurrRoute = New UI.Route(Me.Page)


            DB = mDB.GetDB


            'Me.CurrMainApp = CurrRoute.GetDataInt("AppType")


        End Sub

        Protected Sub PageBaseSite_PreInit(sender As Object, e As System.EventArgs) Handles Me.PreInit



        End Sub
    End Class


    Public Class Browser

        Public Enum BroserType
            Desktop = 1
            Mobile = 2
            Tablet = 3
        End Enum

        Public Type As BroserType


        Public Sub New()

            If IsMobileDevice() Then
                Me.Type = BroserType.Mobile
            ElseIf IsTabletDevice() Then
                Me.Type = BroserType.Tablet
            Else
                Me.Type = BroserType.Desktop
            End If

        End Sub

        'Public Shared Function IsMobileDevice() As Boolean

        '    'http://detectmobilebrowser.com

        '    Dim u As String = Utils.GetValue(HttpContext.Current.Request.ServerVariables, "HTTP_USER_AGENT")
        '    Dim b As New Regex("android.+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|meego.+mobile|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino", RegexOptions.IgnoreCase)
        '    Dim v As New Regex("1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-", RegexOptions.IgnoreCase)
        '    Return b.IsMatch(u) Or v.IsMatch(Left(u, 4))

        'End Function

        'Public Shared Function IsTabletDevice() As Boolean

        '    'http://detectmobilebrowser.com

        '    Dim u As String = Utils.GetValue(HttpContext.Current.Request.ServerVariables, "HTTP_USER_AGENT")
        '    Dim b As New Regex("android.+tablet|ipad|playbook|silk", RegexOptions.IgnoreCase)
        '    Return b.IsMatch(u)

        'End Function

        Public Shared Function IsMobileDevice() As Boolean

            'http://detectmobilebrowser.com


            Dim u As String = ""
            If HttpContext.Current.Request.ServerVariables("HTTP_USER_AGENT") IsNot Nothing Then
                u = HttpContext.Current.Request.ServerVariables("HTTP_USER_AGENT")
            End If
            Dim b As New Regex("android.+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|meego.+mobile|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino", RegexOptions.IgnoreCase)
            Dim v As New Regex("1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-", RegexOptions.IgnoreCase)
            Return b.IsMatch(u) Or v.IsMatch(Left(u, 4))

        End Function

        Public Shared Function IsTabletDevice() As Boolean

            'http://detectmobilebrowser.com

            Dim u As String = ""
            If HttpContext.Current.Request.ServerVariables("HTTP_USER_AGENT") IsNot Nothing Then
                u = HttpContext.Current.Request.ServerVariables("HTTP_USER_AGENT")
            End If
            Dim b As New Regex("android.+tablet|ipad|playbook|silk", RegexOptions.IgnoreCase)
            Return b.IsMatch(u)

        End Function


    End Class


    Public Class AuthUsers
        Inherits UI.AuthUsersBase

        'Private UserConf As String

        Public Sub New()

            MyBase.New("AUTH_USERS")

        End Sub

        Public Overrides Function CheckAccount(Username As String, Password As String) As Boolean

            Return mDB.GetDB.TAB.User.Where("Email", "=", Username, "Password", "=", Password).ToObj IsNot Nothing

        End Function

        Public Overrides Function GetPassword(Username As String) As String

            Dim u = mDB.GetDB.TAB.User.Where("Email", "=", Username).ToObj

            If u Is Nothing Then
                Return ""
            Else
                Return u.Password
            End If

            'Return mDB.GetDB.TabUser.Where("Email", "=", Username).ToObj.Password

        End Function

        Public Overrides Function GetUserData() As Object

            Dim UserData = mDB.GetDB.TAB.User.Where("Email", "=", Me.SessionUsername).ToObj

            If UserData IsNot Nothing Then
                'controllo ulteriore
                If Me.CheckPassword(UserData.Password) Then
                    Return UserData
                Else
                    Me.LogOut()
                    UserData = Nothing
                End If

            End If

            Return UserData


        End Function

        Public Overrides Sub OnLogin()

            MyApp.InitLoginUser()

        End Sub
    End Class

    Public Class LogTime

        Public LogTime As New List(Of LogTimeData)

        Private LastTime As Double = Double.MinValue

        Public Sub AddLog(s As String)
            Dim Diff As Double
            Dim NowTime As Double = Date.UtcNow.Ticks / 10000000

            If LastTime = Double.MinValue Then
                Diff = 0
            Else
                Diff = NowTime - LastTime
            End If

            LastTime = NowTime

            Me.LogTime.Add(New LogTimeData With {.Time = NowTime, .Label = s, .Diff = Diff})

        End Sub


        Public Class LogTimeData

            Private _Time As Double
            Public Property Time() As Double

                Get
                    Return _Time
                End Get
                Set(ByVal value As Double)
                    _Time = value
                End Set
            End Property

            Private _Label As String
            Public Property Label() As String
                Get
                    Return _Label
                End Get
                Set(ByVal value As String)
                    _Label = value
                End Set
            End Property

            Private _Diff As Double
            Public Property Diff() As Double
                Get
                    Return _Diff
                End Get
                Set(ByVal value As Double)
                    _Diff = value
                End Set
            End Property


            'Public Label As String
            'Public Diff As Long

        End Class

    End Class


    'Public Class Charts

    '    Public Shared Sub SetGeoChart(ByRef c As Charting.Chart)
    '        Dim TmpC As New Charting.Chart

    '        'AddHandler TmpC.PreRender, AddressOf aa
    '        'TO DO da sistemare a buco perchè così tutti hanno la stessa immagine
    '        'c.ImageLocation = "~/" & c.ID & Utils.MD5.MD5(HttpContext.Current.Request.Url.AbsolutePath) & ".png"
    '        'c.ImageLocation = "~/charts/" & c.ID & ".png"

    '        'c.ImageStorageMode = Charting.ImageStorageMode.UseImageLocation
    '        c.ImageStorageMode = Charting.ImageStorageMode.UseHttpHandler

    '        'c.Attributes("dir") = "E:\App\Dev\trunk\Main\"

    '        'c.RenderType = Charting.RenderType.ImageTag

    '        'c.BackImage = "~/images/Logo500.png"
    '        'c.BackImageAlignment = Charting.ChartImageAlignmentStyle.Center
    '        'c.BackImageWrapMode = Charting.ChartImageWrapMode.Scaled



    '        If c.BackColor = TmpC.BackColor Then
    '            c.BackColor = Utils.Color.ToCol("#ffffff")
    '            ' c.BackColor = Drawing.Color.FromArgb(&HD3, &HDF, &HF0)
    '        End If
    '        If c.BorderColor = TmpC.BorderColor Then
    '            c.BorderColor = Utils.Color.ToCol("#B54001")
    '        End If
    '        If c.BackGradientStyle = TmpC.BackGradientStyle Then
    '            '   c.BackGradientStyle = Charting.GradientStyle.TopBottom
    '        End If
    '        If c.BorderWidth = TmpC.BorderWidth Then
    '            c.BorderWidth = 0
    '        End If

    '        '----------------------------
    '        ' mega bordone
    '        'If c.BorderlineColor = TmpC.BorderlineColor Then
    '        '    c.BorderlineColor = Utils.Color.ToCol("#B54001")
    '        '    'c.BorderlineColor = Drawing.Color.Transparent

    '        'End If
    '        'If c.BorderlineDashStyle = TmpC.BorderlineDashStyle Then
    '        '    c.BorderlineDashStyle = Charting.ChartDashStyle.Solid
    '        'End If
    '        'If c.BorderlineWidth = TmpC.BorderlineWidth Then
    '        '    c.BorderlineWidth = 2
    '        'End If

    '        'If c.BorderSkin.SkinStyle = TmpC.BorderSkin.SkinStyle Then
    '        '    c.BorderSkin.SkinStyle = Charting.BorderSkinStyle.Emboss
    '        '    'c.BorderSkin.PageColor = Drawing.Color.Transparent
    '        'End If
    '        '----------------------------
    '        ' mega bordone


    '        If c.ChartAreas.Count = 0 Then
    '            c.ChartAreas.Add(DefautArea(1))
    '            SetArea(c.ChartAreas("Area1"))

    '            'c.ChartAreas(0).AxisY.LabelStyle.Font = New Drawing.Font("Arial", 11, Drawing.GraphicsUnit.Pixel)
    '            'c.ChartAreas(0).AxisX.LabelStyle.Font = New Drawing.Font("Arial", 11, Drawing.GraphicsUnit.Pixel)

    '            'c.ChartAreas(0).AxisY.LabelStyle.Font = New Drawing.Font("Arial", 11, Drawing.GraphicsUnit.Pixel)
    '            'c.ChartAreas(0).AxisX.IsLabelAutoFit = False
    '            '                        .LabelStyle = New Charting.LabelStyle With {.Font = New Drawing.Font("Trebuchet MS", 17, Drawing.FontStyle.Underline, Drawing.GraphicsUnit.Point)},

    '        End If

    '    End Sub

    '    Public Shared Sub SetArea(area As Charting.ChartArea)

    '        With area

    '            With .AxisX
    '                .LabelStyle.Font = New Drawing.Font("Arial", 11, Drawing.GraphicsUnit.Pixel)
    '                .IntervalAutoMode = DataVisualization.Charting.IntervalAutoMode.VariableCount
    '                '.IntervalType = Charting.DateTimeIntervalType.Hours

    '                .IsLabelAutoFit = True
    '                .LabelAutoFitStyle = DataVisualization.Charting.LabelAutoFitStyles.WordWrap + DataVisualization.Charting.LabelAutoFitStyles.LabelsAngleStep30 + DataVisualization.Charting.LabelAutoFitStyles.StaggeredLabels
    '            End With

    '            With .AxisY
    '                .LabelStyle.Font = New Drawing.Font("Arial", 11, Drawing.GraphicsUnit.Pixel)
    '                .IntervalAutoMode = DataVisualization.Charting.IntervalAutoMode.VariableCount
    '                .IsLabelAutoFit = True
    '                .LabelAutoFitStyle = DataVisualization.Charting.LabelAutoFitStyles.WordWrap + DataVisualization.Charting.LabelAutoFitStyles.LabelsAngleStep30 + DataVisualization.Charting.LabelAutoFitStyles.StaggeredLabels

    '            End With

    '            With .AxisY2
    '                .LabelStyle.Font = New Drawing.Font("Arial", 11, Drawing.GraphicsUnit.Pixel)
    '                .IntervalAutoMode = DataVisualization.Charting.IntervalAutoMode.VariableCount
    '                .IsLabelAutoFit = True
    '                .LabelAutoFitStyle = DataVisualization.Charting.LabelAutoFitStyles.WordWrap + DataVisualization.Charting.LabelAutoFitStyles.LabelsAngleStep30 + DataVisualization.Charting.LabelAutoFitStyles.StaggeredLabels

    '            End With



    '        End With


    '    End Sub

    '    'Public Shared Function DefautArea(ByVal N As Integer) As Charting.ChartArea

    '    '    Dim area = New Charting.ChartArea With {
    '    '        .Name = "Area" & N.ToString
    '    '    }

    '    '    Return area

    '    'End Function

    '    Public Shared Function DefautArea(ByVal N As Integer) As Charting.ChartArea

    '        Dim area = New Charting.ChartArea With {
    '            .Name = "Area" & N.ToString,
    '            .BorderColor = Drawing.Color.FromArgb(64, 64, 64, 64),
    '            .BackSecondaryColor = Drawing.Color.White,
    '            .BackColor = Drawing.Color.Transparent,
    '            .ShadowColor = Drawing.Color.Transparent,
    '            .AxisY = New Charting.Axis With {
    '                .LineColor = Utils.Color.ToCol("#CCCCCC"),
    '                .MajorGrid = New Charting.Grid With {.LineColor = Utils.Color.ToCol("#CCCCCC")},
    '                .MajorTickMark = New Charting.TickMark With {.Size = 0D}
    '            },
    '            .AxisX = New Charting.Axis With {
    '                .LineColor = Utils.Color.ToCol("#CCCCCC "),
    '                .MajorGrid = New Charting.Grid With {.LineColor = Utils.Color.ToCol("#CCCCCC", 0)}
    '            },
    '            .AxisY2 = New Charting.Axis With {
    '                .LineColor = Utils.Color.ToCol("#CCCCCC"),
    '                .MajorGrid = New Charting.Grid With {.LineColor = Utils.Color.ToCol("#CCCCCC", 0)},
    '                .MajorTickMark = New Charting.TickMark With {.Size = 0.6D}
    '            }
    '        }


    '        area.AxisY.LabelStyle.ForeColor = Utils.Color.ToCol("#666666")
    '        area.AxisX.LabelStyle.ForeColor = Utils.Color.ToCol("#666666")
    '        'area.AxisY.LabelStyle.Font = New Drawing.Font("arial", 7, Drawing.GraphicsUnit.Pixel)
    '        'area.AxisX.LabelStyle.Font = New Drawing.Font("Arial", 7, Drawing.GraphicsUnit.Pixel)
    '        'area.AxisY2.LabelStyle.Font = New Drawing.Font("Arial", 7, Drawing.GraphicsUnit.Pixel)
    '        'area.AxisY.LabelStyle.Font.FontFamil = New System.Drawing.FontFamily("arial")

    '        Return area

    '    End Function

    '    Public Shared Sub SetSiteChart(ByRef c As Charting.Chart)
    '        Dim TmpC As New Charting.Chart

    '        'AddHandler TmpC.PreRender, AddressOf aa

    '        c.ImageLocation = "~/Site/Charts/" & c.ID & "/" & Utils.MD5.MD5(HttpContext.Current.Request.Url.AbsolutePath) & ".png"
    '        c.ImageStorageMode = Charting.ImageStorageMode.UseImageLocation

    '        'c.BackImage = "~/images/Logo500.png"
    '        'c.BackImageAlignment = Charting.ChartImageAlignmentStyle.Center
    '        'c.BackImageWrapMode = Charting.ChartImageWrapMode.Scaled



    '        If c.BackColor = TmpC.BackColor Then
    '            'c.BackColor = Drawing.Color.FromArgb(243, 223, 193)
    '            c.BackColor = Drawing.Color.FromArgb(230, 230, 230)
    '        End If
    '        If c.BorderColor = TmpC.BorderColor Then
    '            c.BorderColor = Utils.Color.ToCol("#B54001")
    '        End If
    '        If c.BackGradientStyle = TmpC.BackGradientStyle Then
    '            c.BackGradientStyle = Charting.GradientStyle.TopBottom
    '        End If
    '        If c.BorderWidth = TmpC.BorderWidth Then
    '            c.BorderWidth = 0
    '        End If
    '        If c.BorderlineColor = TmpC.BorderlineColor Then
    '            'c.BorderlineColor = Drawing.Color.FromName("DarkRed")
    '            c.BorderlineColor = Drawing.Color.Transparent

    '        End If
    '        If c.BorderlineDashStyle = TmpC.BorderlineDashStyle Then
    '            c.BorderlineDashStyle = Charting.ChartDashStyle.Solid
    '        End If
    '        If c.BorderlineWidth = TmpC.BorderlineWidth Then
    '            c.BorderlineWidth = 0
    '        End If

    '        If c.BorderSkin.SkinStyle = TmpC.BorderSkin.SkinStyle Then
    '            c.BorderSkin.SkinStyle = Charting.BorderSkinStyle.Emboss
    '            'c.BorderSkin.PageColor = Drawing.Color.Transparent

    '        End If

    '        If c.ChartAreas.Count = 0 Then
    '            c.ChartAreas.Add(New Charting.ChartArea With {
    '                .Name = "ChartArea1",
    '                .BorderColor = Drawing.Color.FromArgb(64, 64, 64, 64),
    '                .BackSecondaryColor = Drawing.Color.White,
    '                .BackColor = Drawing.Color.Transparent,
    '                .ShadowColor = Drawing.Color.Transparent,
    '                .AxisY = New Charting.Axis With {
    '                    .LineColor = Drawing.Color.FromArgb(64, 64, 64, 64),
    '                    .MajorGrid = New Charting.Grid With {.LineColor = Drawing.Color.FromArgb(64, 64, 64, 64)},
    '                    .MajorTickMark = New Charting.TickMark With {.Size = 0.6D}
    '                },
    '                .AxisX = New Charting.Axis With {
    '                    .LineColor = Drawing.Color.FromArgb(64, 64, 64, 64),
    '                    .MajorGrid = New Charting.Grid With {.LineColor = Drawing.Color.FromArgb(64, 64, 64, 64)}
    '                }
    '            })
    '            c.ChartAreas(0).AxisY.LabelStyle.Font = New Drawing.Font("Arial", 11, Drawing.GraphicsUnit.Pixel)
    '            c.ChartAreas(0).AxisX.LabelStyle.Font = New Drawing.Font("Arial", 11, Drawing.GraphicsUnit.Pixel)
    '            'c.ChartAreas(0).AxisX.IsLabelAutoFit = False
    '            '                        .LabelStyle = New Charting.LabelStyle With {.Font = New Drawing.Font("Trebuchet MS", 17, Drawing.FontStyle.Underline, Drawing.GraphicsUnit.Point)},

    '        End If



    '        '<asp:Chart ID="ChartImage" ImageLocation="~/graf" ImageStorageMode="UseImageLocation" runat="server" Width="400px" BackColor="243, 223, 193" BorderColor="#B54001" BackGradientStyle="TopBottom" BorderWidth="2px" BorderlineColor="DarkRed" BorderlineDashStyle="Solid" BorderlineWidth="2">
    '        '    <BorderSkin SkinStyle="Emboss" PageColor="Transparent" BackColor=""></BorderSkin>
    '        '    <ChartAreas>
    '        '        <asp:ChartArea Name="ChartArea1" BorderColor="64, 64, 64, 64" BackSecondaryColor="White" BackColor="OldLace" ShadowColor="Transparent">
    '        '            <AxisY LineColor="64, 64, 64, 64">
    '        '                <LabelStyle Font="Trebuchet MS, 8.25pt, style=Bold" />
    '        '                <MajorGrid LineColor="64, 64, 64, 64" />
    '        '                <MajorTickMark Size="0.6" />
    '        '            </AxisY>
    '        '            <AxisX LineColor="64, 64, 64, 64">
    '        '                <LabelStyle Font="Trebuchet MS, 8.25pt, style=Bold" />
    '        '                <MajorGrid LineColor="64, 64, 64, 64" />
    '        '            </AxisX>
    '        '        </asp:ChartArea>
    '        '    </ChartAreas>
    '        '</asp:Chart>
    '    End Sub



    '    Public Shared Function DefautTitle(ByVal Title As String) As Charting.Title


    '        Return New Charting.Title With {
    '            .Text = Title,
    '            .Font = New Drawing.Font("Trebuchet MS", 11.0, Drawing.FontStyle.Bold),
    '            .ShadowOffset = 0,
    '            .ForeColor = Drawing.Color.FromArgb(26, 59, 105)
    '        }
    '        '        <asp:Title ShadowColor="32, 0, 0, 0" Font="Trebuchet MS, 14.25pt, style=Bold" ShadowOffset="3" Text="Radar Chart" ForeColor="26, 59, 105"></asp:Title>


    '    End Function

    '    Public Shared Function DefautSerie(ByVal N As Integer, ByVal t As Charting.SeriesChartType) As Charting.Series

    '        Return DefautSerie(N, t, "")

    '    End Function
    '    Public Shared Function DefautSerie(ByVal N As Integer, ByVal t As Charting.SeriesChartType, ByVal Name As String) As Charting.Series
    '        Dim c As Drawing.Color

    '        Select Case N
    '            Case 1
    '                'c = Drawing.Color.FromArgb(220, 65, 140, 240)
    '                c = Utils.Color.ToCol("#FFD203")

    '            Case 2
    '                c = Drawing.Color.FromArgb(220, 252, 180, 65)
    '            Case 3
    '                c = Drawing.Color.FromArgb(220, 0, 0, 252)
    '            Case Else
    '                c = Drawing.Color.FromArgb(220, 0, 252, 0)
    '        End Select

    '        'Return New Charting.Series With {
    '        '    .Name = "Series" & N.ToString,
    '        '    .ChartType = t,
    '        '    .markerBorderColor = Drawing.Color.FromArgb(64, 64, 64),
    '        '    .markerSize = 5,
    '        '    .borderColor = Drawing.Color.FromArgb(180, 26, 59, 105),
    '        '    .color = c,
    '        '    .ShadowOffset = 1,
    '        '    .legendText = Name
    '        '}

    '        Return New Charting.Series With {
    '            .Name = "Series" & N.ToString,
    '            .ChartType = t,
    '            .markerBorderColor = Drawing.Color.FromArgb(64, 64, 64),
    '            .markerSize = 5,
    '            .borderColor = Drawing.Color.FromArgb(180, 26, 59, 105),
    '            .color = c,
    '            .borderWidth = 0,
    '            .ShadowOffset = 0,
    '            .legendText = Name
    '        }
    '        '        <asp:Series MarkerBorderColor="64, 64, 64" MarkerSize="9" Name="Series1" ChartType="radar" BorderColor="180, 26, 59, 105" Color="220, 65, 140, 240" ShadowOffset="1"></asp:Series>

    '    End Function

    '    Public Shared Function DefautLegend() As Charting.Legend

    '        Return New Charting.Legend With {
    '            .Name = "Default",
    '            .BackColor = Drawing.Color.Transparent,
    '            .Font = New Drawing.Font("Arial", 11, Drawing.GraphicsUnit.Pixel),
    '            .LegendStyle = Charting.LegendStyle.Table,
    '            .Docking = Charting.Docking.Bottom
    '        }
    '        '        <asp:Legend Name="Default" BackColor="Transparent" Font="Trebuchet MS, 8pt, style=Bold">        </asp:Legend>
    '        'ChartAgesStat.Legends(0).LegendStyle = DataVisualization.Charting.LegendStyle.Row
    '        'ChartAgesStat.Legends(0).Docking = DataVisualization.Charting.Docking.Bottom

    '    End Function

    '    Public Shared Function DefaultHorizontalLine(ByRef c As Charting.Chart, ByVal y As Double, ByVal LineDashStyle As Charting.ChartDashStyle, ByVal LineWidth As Integer) As Charting.HorizontalLineAnnotation

    '        Return New Charting.HorizontalLineAnnotation With {
    '            .Alignment = Drawing.ContentAlignment.BottomCenter,
    '            .AxisX = c.ChartAreas(0).AxisX,
    '            .AxisY = c.ChartAreas(0).AxisY,
    '            .ClipToChartArea = c.ChartAreas(0).Name,
    '            .LineColor = Drawing.Color.Maroon,
    '            .LineDashStyle = LineDashStyle,
    '            .LineWidth = LineWidth,
    '            .Width = 100,
    '            .X = 0,
    '            .Y = y
    '        }

    '    End Function
    '    Public Shared Function CustomPoint(ByVal AxisLabel As String, ByVal y As Double, ByVal c As Drawing.Color) As Charting.DataPoint

    '        Return New Charting.DataPoint With {.AxisLabel = AxisLabel, .YValues = New Double() {y}, .Color = c}

    '    End Function




    'End Class



    Public Class Routes

        Private Shared Function GetDefPageValue() As Object
            Return New Routing.RouteValueDictionary(New With {
                .page = "default.aspx"
            })

        End Function

        Public Shared Sub RegisterRoutes(ByVal routes As Routing.RouteCollection)

            Dim SiteName = ""

            'routes.Ignore("{resource}.axd")
            routes.Ignore("{resource}.axd/{*pathInfo}")
            routes.Ignore("{resource}.ico")
            routes.Ignore("{resource}.css")


            routes.Add(New Routing.Route("api/v1/folder/{*pathInfo}", New WebServiceRouteHandler("~/webservice/folder.asmx")))

            AddRouteName(routes, "API_FOLDER", "API/FOLDER/{*pathInfo}", "~/api/folder.aspx", Nothing, Nothing, Nothing)

            routes.Add(New ServiceModel.Activation.ServiceRoute("prova", New ServiceModel.Activation.WebServiceHostFactory, GetType(ServiceProva)))
            routes.Add(New ServiceModel.Activation.ServiceRoute("API/prova", New ServiceModel.Activation.WebServiceHostFactory, GetType(ServiceProva)))



            '------------------------------------------------------------
            ' DEMO
            '------------------------------------------------------------

            'AddRouteName(routes, "WS", "api/v1/folder", "~/webservice/folder.asmx", Nothing, Nothing, Nothing)

            '''''''''''''''''''''''
            ' MAIN
            AddRouteName(routes, "HOME", SiteName & "", "~/App/default.aspx", Nothing, Nothing, Nothing)
            AddRouteName(routes, "DASHBOARD", SiteName & "DASHBOARD", "~/App/Dashboard.aspx", Nothing, Nothing, Nothing)
            AddRouteName(routes, "SOCIAL_SEO", SiteName & "SOCIAL_SEO", "~/App/SocialSEO.aspx", Nothing, Nothing, Nothing)
            AddRouteName(routes, "SCHEDULE", SiteName & "SCHEDULE", "~/App/Schedule.aspx", Nothing, Nothing, Nothing)
            AddRouteName(routes, "LISTEN", SiteName & "LISTEN", "~/App/Listen.aspx", Nothing, Nothing, Nothing)
            'crm
            AddRouteName(routes, "CONNECTIONS", SiteName & "CONNECTIONS", "~/App/connections.aspx", Nothing, Nothing, Nothing)
            AddRouteName(routes, "CATEGORIZE", SiteName & "CATEGORIZE", "~/App/Categorize.aspx", Nothing, Nothing, Nothing)
            'follow
            AddRouteName(routes, "FOLLOW", SiteName & "FOLLOW", "~/App/Follow.aspx", Nothing, Nothing, Nothing)
            'AddRouteName(routes, "FOLLOW_LIST", SiteName & "FOLLOW_LIST", "~/App/FollowList.aspx", Nothing, Nothing, Nothing)
            AddRouteName(routes, "FOLLOW_STAT", SiteName & "FOLLOW_STAT", "~/App/FollowStat.aspx", Nothing, Nothing, Nothing)
            AddRouteName(routes, "HASHTAGS_MONITOR", SiteName & "HASHTAGS_MONITOR", "~/App/HashtagsMonitor.aspx", Nothing, Nothing, Nothing)

            AddRouteName(routes, "POST_SEARCH", SiteName & "POST_SEARCH", "~/App/PostSearch.aspx", Nothing, Nothing, Nothing)


            AddRouteName(routes, "USERACCOUNTS", SiteName & "USERACCOUNTS", "~/App/Useraccounts.aspx", Nothing, Nothing, Nothing)
            AddRouteName(routes, "BILLING", SiteName & "BILLING", "~/App/Billing.aspx", Nothing, Nothing, Nothing)


            'AddRouteName(routes, "HASHTAG", SiteName & "hashtag", "~/App/FollowingRealTime.aspx", Nothing, Nothing, Nothing)
            'AddRouteName(routes, "APP", SiteName & "app/{*page}", "~/App/{page}", GetDefPageValue, Nothing, Nothing)
            'AddRouteName(routes, "SITE", SiteName & "site/{*page}", "~/site/{page}", GetDefPageValue, Nothing, Nothing)
            'AddRouteName(routes, "APP2", SiteName & "app/{page}/pp/", "~/App/test/pp/default.aspx", GetDefPageValue, Nothing, Nothing)




        End Sub


        Public Shared Sub AddRouteName(ByVal routes As Routing.RouteCollection, ByVal RouteName As String, ByVal routeurl As String, ByVal phisicalFile As String, ByVal defaults As Routing.RouteValueDictionary, ByVal contraints As Routing.RouteValueDictionary, ByVal dataTokens As Routing.RouteValueDictionary)

            If dataTokens Is Nothing Then
                dataTokens = New Routing.RouteValueDictionary()
            End If

            dataTokens.Add("RouteName", RouteName.ToUpper)

            routes.MapPageRoute(RouteName.ToUpper, routeurl, phisicalFile, False, defaults, contraints, dataTokens)

        End Sub

    End Class

    Public Class WebServiceRouteHandler2
        Implements Routing.IRouteHandler

        Private virtualPath As String

        Public Sub New(virtualPath As String)
            Me.virtualPath = virtualPath
        End Sub


        Public Function GetHttpHandler(requestContext As Routing.RequestContext) As IHttpHandler Implements Routing.IRouteHandler.GetHttpHandler

            Return New System.Web.Services.Protocols.WebServiceHandlerFactory().GetHandler(HttpContext.Current, "*", Me.virtualPath, HttpContext.Current.Server.MapPath(Me.virtualPath))

            ' Return _                                             handlerFactory.GetHandler(HttpContext.Current, requestContext.HttpContext.Request.HttpMethod, _virtualPath, requestContext.HttpContext.Server.MapPath(_virtualPath))

        End Function
    End Class


    Public Class WebServiceRouteHandler
        Implements Routing.IRouteHandler

        Private Shared ScriptHandlerFactory As IHttpHandlerFactory
        Shared Sub New()
            Dim assembly = GetType(System.Web.Script.Services.ScriptMethodAttribute).Assembly
            Dim type = assembly.[GetType]("System.Web.Script.Services.ScriptHandlerFactory")
            ScriptHandlerFactory = DirectCast(Activator.CreateInstance(type, True), IHttpHandlerFactory)
        End Sub

        Private virtualPath As String
        Public Sub New(virtualPath As String)
            Me.virtualPath = virtualPath
        End Sub

        Public Function GetHttpHandler(requestContext As Routing.RequestContext) As IHttpHandler Implements Routing.IRouteHandler.GetHttpHandler
            Dim pathInfo As String = TryCast(requestContext.RouteData.Values("pathInfo"), String)
            If Not String.IsNullOrWhiteSpace(pathInfo) Then
                pathInfo = String.Format("/{0}", pathInfo)
            End If

            requestContext.HttpContext.RewritePath(Me.virtualPath, pathInfo, requestContext.HttpContext.Request.QueryString.ToString())
            Dim handler = ScriptHandlerFactory.GetHandler(HttpContext.Current, requestContext.HttpContext.Request.HttpMethod, Me.virtualPath, requestContext.HttpContext.Server.MapPath(Me.virtualPath))
            Return handler
        End Function
    End Class
End Namespace